import os.path
import re
import time

# from bs4 import BeautifulSoup
import requests
from PIL import Image

from utils.compress_images import compress_image
from config.settings import UPLOAD_FOLDER

html = '''<p>
    <img src="	https://ertucdn.cdn.bcebos.com/uploads/images/202406/20240607/b41c516c71d550b74f281e6d66a5316b.jpg"/>
</p>'''


# 解析文章内容中的图片地址
def parse_image_url(content):
    # img_path = re.search('<img src="(.+?)"', htmls)
    # return img_path.group(1)
    # bs_obj = BeautifulSoup(htmls, 'html.parser')
    # img_obj = bs_obj.find("img")
    temp_list = re.findall('<img src="(.+?)"', content)
    url_list = []
    for url in temp_list:
        # 如果图片类型为gif，则直接跳过，不对其作任何处理
        if url.lower().endswith('.gif'):
            continue
        url_list.append(url)
    return url_list


# 远程下载指定URL地址的图片，并保存到指定目录
def download_image(url, dest):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        'Referer': os.path.dirname(url)
    }

    os.makedirs(os.path.dirname(dest), exist_ok=True)

    with requests.get(url, headers=headers, stream=True, timeout=15) as resp:
        resp.raise_for_status()
        if 'image' not in resp.headers.get('Content-Type', ''):
            raise ValueError('返回的不是图片')

        with open(dest, 'wb') as f:
            for chunk in resp.iter_content(1024):
                if chunk:
                    f.write(chunk)

    # 验证文件是否真的是图片
    try:
        with Image.open(dest) as im:
            im.verify()  # 仅做完整性验证
    except Exception as e:
        os.remove(dest)
        raise ValueError(f'下载的文件不是有效图片: {e}')


def generate_thumbnail(url_list):
    # 根据解析出来的图片地址进行提取缩略图
    # 文章中如果是上传的图片则提取第一张进行压缩后存到缩略图文件夹中
    # 如果是网络图片，则下载后进行压缩放到缩略图文件夹去
    for item in url_list:
        if item.startswith('/upload'):
            # filename = item.split('/')[-1]
            # subdir = time.strftime("%Y%m%d")
            # 找到本地图片后进行压缩处理，宽度设置为400
            raw_path = os.path.dirname(UPLOAD_FOLDER) + item
            source = os.path.normcase(raw_path)
            thumb_filename = item.replace('/upload/', "")
            dest = os.path.normpath(os.path.join(UPLOAD_FOLDER, 'thumb', thumb_filename))
            compress_image(source, dest, 400)
            return thumb_filename  # 找到第一张就返回
    # 如果没有找到则网上url地址下载后再处理
    url = url_list[0]  # 这个就是第一张在线图的rul地址
    filename = url.split('/')[-1]
    suffix = filename.split('.')[-1]  # 取得后缀名字
    thumbnail_name = time.strftime("%Y%m%d_%H%M%S." + suffix)
    tempfile = os.path.join(UPLOAD_FOLDER, 'temp_download', thumbnail_name)
    download_image(url.strip(), tempfile)
    thumbnail_path = os.path.join(UPLOAD_FOLDER, 'thumb', thumbnail_name)
    compress_image(tempfile, thumbnail_path, 400)
    return thumbnail_name


name = generate_thumbnail(parse_image_url(html))
